<?php
/**
 * tpAdmin [a web admin based ThinkPHP5]
 *
 * @author yuan1994 <tianpian0805@gmail.com>
 * @link http://tpadmin.yuan1994.com/
 * @copyright 2016 yuan1994 all rights reserved.
 * @license http://www.apache.org/licenses/LICENSE-2.0
 */

//------------------------
// 角色控制器
//-------------------------

namespace app\admin\controller;

\think\Loader::import('controller/Controller', \think\Config::get('traits_path') , EXT);

use app\admin\Controller;
use think\Exception;
use think\Db;
use think\Loader;

class AdminRole extends Controller
{
    use \app\admin\traits\controller\Controller;

//    protected static $blacklist = ['recyclebin', 'delete', 'recycle', 'deleteforever', 'clear'];

    protected function filter(&$map)
    {
        if ($this->request->param('name')) {
            $map['name'] = ["like", "%" . $this->request->param('name') . "%"];
        }
    }
    
    //
    public function index()
    {
        $data = input();
        if ($data['name']){
            $map['name'] = ['like','%'.$data['name'].'%'];
        }
        $map['isdelete'] = 0;
        $list = Db::name('admin_role')->where($map)->select();
        $info = Db::name('information')->field('id,value,role_ids')->select();
        $infoArr = [];
        foreach ($info as $ik=>$iv){
            if (!empty($iv['role_ids'])){
                $infoArr[$iv['value']] = explode(',',$iv['role_ids']);
            }
        }
        $this->view->assign('info',$infoArr);
        $this->view->assign('list',$list);
        return $this->view->fetch();
    }

    /**
     * 用户列表
     */
    public function user()
    {
        $role_id = $this->request->param('id/d');
        if ($this->request->isPost()) {
            // 提交
            if (!$role_id) {
                return ajax_return_adv_error("缺少必要参数");
            }
            $data = input();
            //过滤取消选择的用户
            if ($data['user_id']){
                $user_id = $data['user_id'];
            }
            if ($data['check_user'] != 'unselected'){//搜索之前已选择的用户
//                dump('cunzai');
                $check_user_id = explode(',',$data['check_user']);
                $del_user_id = '';
                if (!empty($user_id)){//存在选择的用户
                    foreach ($check_user_id as $ck=>$cv){
                        if (!in_array($cv,$user_id)){
                            $del_user_id .= $cv.',';
                        }
                    }
                    $del_user_id = explode(',',rtrim($del_user_id,','));//要删除的用户id
                    //删除已取消的用户
                    if (!empty($del_user_id)){
                        foreach ($del_user_id as $dk=>$dv){
                        $re = Db::name('admin_role_user')
                            ->where('role_id',$data['id'])
                            ->where('user_id',$dv)
                            ->delete();
//                        dump($re);
                        }
                    }
                    //寻找角色还存在的用户
                    $role_data = Db::name('admin_role_user')->where('role_id',$data['id'])->select();
                    Db::name('admin_role_user')->where('role_id',$data['id'])->delete();
                    if (!empty($role_data)){
                        foreach ($role_data as $rrk=>$rvv){
                            if (!in_array($rvv['user_id'],$user_id)){
                                $user_id[] = $rvv['user_id'];
                            }
                        }
                    }
//                    dump($user_id);
                    $insert = [];
                    foreach ($user_id as $uk=>$uv){
                        $insert[$uk]['user_id'] = intval($uv);
                        $insert[$uk]['role_id'] = $data['id'];
                    }
//                    dump($insert);
                    //添加角色用户
                    $up = Db::name('admin_role_user')->strict(false)->insertAll($insert);
//                    dump($up);
                    logs('insert',$up);
                    return ajax_return_adv("分配角色成功", '');
                }else{
                    //把选择的角色用户id全删
                    $check_user_id = explode(',',$data['check_user']);
//                    dump($check_user_id);
                    foreach ($check_user_id as $ck=>$cv){
                        $del = Db::name('admin_role_user')->where('role_id',$data['id'])
                                                        ->where('user_id',$cv)->delete();
                    }
                    return ajax_return_adv("分配角色成功", '');
                }
            }else{
                $role_data = Db::name('admin_role_user')->where('role_id',$data['id'])->select();
                Db::name('admin_role_user')->where('role_id',$data['id'])->delete();
                if (!empty($role_data) || !empty($user_id)){
                    if (!empty($role_data) && !empty($user_id)){
                        foreach ($role_data as $rrk=>$rvv){
                            if (!in_array($rvv['user_id'],$user_id)){
                                $user_id[] = $rvv['user_id'];
                            }
                        }
                    }elseif(!empty($role_data)){
                        foreach ($role_data as $rrk=>$rrv){
                            $user_id[] = $rrv['user_id'];
                        }
                    }
                    $insert = [];
                    foreach ($user_id as $uk=>$uv){
                        $insert[$uk]['user_id'] = intval($uv);
                        $insert[$uk]['role_id'] = $data['id'];
                    }
                    $up = Db::name('admin_role_user')->strict(false)->insertAll($insert);
                    logs('up',$up);
                    return ajax_return_adv("分配角色成功", '');
                }
                return ajax_return_adv("分配角色成功", '');
            }
        } else {
            // 编辑页

            $data = input();
            if ($data['role_id']){
                $role_id = $data['role_id'];
            }
            if (!$role_id) {
                throw new Exception("缺少必要参数");
            }
            if ($data['role_id']){// 搜索
                $list_data = $this->search_users($data);
                $list = $list_data['list'];
                $check_user = $list_data['check_user'];
                $checks = $list_data['checks'];
                $role_id = $data['role_id'];
                $this->view->assign('check_user', $check_user);
                $this->view->assign('list', $list);
                $this->view->assign('checks', $checks);
                $this->view->assign('role_id', $role_id);

                return $this->view->fetch();
            }
            if ($data['realname']){
                $map['u.realname'] = ['like','%'.$data['realname'].'%'];
            }
            if ($data['account']){
                $map['u.account'] = ['like','%'.$data['account'].'%'];
            }
            // 读取系统的用户列表
            $list_user = Db::name("admin_user_info")
                ->alias('u')
                ->join('tp_admin_role_user ru',"ru.user_id=u.id",'left')
                ->field('u.id,u.account,u.realname')
                ->where($map)
                ->where('u.status=1 AND u.id > 1 AND ru.user_id is null')
                ->select();

            // 已授权权限
            $list_role_user = Db::name("AdminRoleUser")->where("role_id", $role_id)->select();


            $checks = filter_value($list_role_user, "user_id", true);


            $check_user = Db::name("admin_user_info")
                ->alias('u')
                ->join('tp_admin_role_user ru',"ru.user_id=u.id and ru.role_id=$role_id",'left')
                ->field('u.id,u.account,u.realname')
                ->where('u.status=1 AND u.id > 1 and ru.role_id='.$role_id)
                ->select();

            $this->view->assign('check_user', $check_user);
            $this->view->assign('list', $list_user);
            $this->view->assign('checks', $checks);
            $this->view->assign('role_id', $role_id);

            return $this->view->fetch();
        }
    }

    //备份用户角色列表
    public function user_beifen()
    {
        $role_id = $this->request->param('id/d');
        if ($this->request->isPost()) {
            // 提交
            if (!$role_id) {
                return ajax_return_adv_error("缺少必要参数");
            }
            $data = input();
            //过滤取消选择的用户
            if ($data['user_id']){
                $user_id = $data['user_id'];
            }
            if ($data['check_user'] != 'unselected'){//搜索之前已选择的用户
//                dump('cunzai');
                $check_user_id = explode(',',$data['check_user']);
                $del_user_id = '';
                if (!empty($user_id)){//存在选择的用户
                    foreach ($check_user_id as $ck=>$cv){
                        if (!in_array($cv,$user_id)){
                            $del_user_id .= $cv.',';
                        }
                    }
                    $del_user_id = explode(',',rtrim($del_user_id,','));//要删除的用户id
                    //删除已取消的用户
                    if (!empty($del_user_id)){
                        foreach ($del_user_id as $dk=>$dv){
                            $re = Db::name('admin_role_user')
                                ->where('role_id',$data['id'])
                                ->where('user_id',$dv)
                                ->delete();
//                        dump($re);
                        }
                    }
                    //寻找角色还存在的用户
                    $role_data = Db::name('admin_role_user')->where('role_id',$data['id'])->select();
                    Db::name('admin_role_user')->where('role_id',$data['id'])->delete();
                    if (!empty($role_data)){
                        foreach ($role_data as $rrk=>$rvv){
                            if (!in_array($rvv['user_id'],$user_id)){
                                $user_id[] = $rvv['user_id'];
                            }
                        }
                    }
//                    dump($user_id);
                    $insert = [];
                    foreach ($user_id as $uk=>$uv){
                        $insert[$uk]['user_id'] = intval($uv);
                        $insert[$uk]['role_id'] = $data['id'];
                    }
//                    dump($insert);
                    //添加角色用户
                    $up = Db::name('admin_role_user')->strict(false)->insertAll($insert);
//                    dump($up);
                    logs('insert',$up);
                    return ajax_return_adv("分配角色成功", '');
                }else{
                    //把选择的角色用户id全删
                    $check_user_id = explode(',',$data['check_user']);
//                    dump($check_user_id);
                    foreach ($check_user_id as $ck=>$cv){
                        $del = Db::name('admin_role_user')->where('role_id',$data['id'])
                            ->where('user_id',$cv)->delete();
                    }
                    return ajax_return_adv("分配角色成功", '');
                }
            }else{
                $role_data = Db::name('admin_role_user')->where('role_id',$data['id'])->select();
                Db::name('admin_role_user')->where('role_id',$data['id'])->delete();
                if (!empty($role_data) || !empty($user_id)){
                    if (!empty($role_data) && !empty($user_id)){
                        foreach ($role_data as $rrk=>$rvv){
                            if (!in_array($rvv['user_id'],$user_id)){
                                $user_id[] = $rvv['user_id'];
                            }
                        }
                    }elseif(!empty($role_data)){
                        foreach ($role_data as $rrk=>$rrv){
                            $user_id[] = $rrv['user_id'];
                        }
                    }
                    $insert = [];
                    foreach ($user_id as $uk=>$uv){
                        $insert[$uk]['user_id'] = intval($uv);
                        $insert[$uk]['role_id'] = $data['id'];
                    }
                    $up = Db::name('admin_role_user')->strict(false)->insertAll($insert);
                    logs('up',$up);
                    return ajax_return_adv("分配角色成功", '');
                }
                return ajax_return_adv("分配角色成功", '');
            }
        } else {
            // 编辑页

            $data = input();
            if ($data['role_id']){
                $role_id = $data['role_id'];
            }
            if (!$role_id) {
                throw new Exception("缺少必要参数");
            }
            if ($data['role_id']){// 搜索
                $list_data = $this->search_users($data);
                $list = $list_data['list'];
                $check_user = $list_data['check_user'];
                $checks = $list_data['checks'];
                $role_id = $data['role_id'];
                $this->view->assign('check_user', $check_user);
                $this->view->assign('list', $list);
                $this->view->assign('checks', $checks);
                $this->view->assign('role_id', $role_id);

                return $this->view->fetch();
            }
            if ($data['realname']){
                $map['u.realname'] = ['like','%'.$data['realname'].'%'];
            }
            if ($data['account']){
                $map['u.account'] = ['like','%'.$data['account'].'%'];
            }
            // 读取系统的用户列表
            $list_user = Db::name("AdminUser")
                ->alias('u')
                ->join('tp_admin_role_user ru',"ru.user_id=u.id",'left')
                ->field('u.id,u.account,u.realname')
                ->where($map)
                ->where('u.status=1 AND u.id > 1 AND ru.user_id is null')
                ->select();

            // 已授权权限
            $list_role_user = Db::name("AdminRoleUser")->where("role_id", $role_id)->select();


            $checks = filter_value($list_role_user, "user_id", true);


            $check_user = Db::name("AdminUser")
                ->alias('u')
                ->join('tp_admin_role_user ru',"ru.user_id=u.id and ru.role_id=$role_id",'left')
                ->field('u.id,u.account,u.realname')
                ->where('u.status=1 AND u.id > 1 and ru.role_id='.$role_id)
                ->select();

            $this->view->assign('check_user', $check_user);
            $this->view->assign('list', $list_user);
            $this->view->assign('checks', $checks);
            $this->view->assign('role_id', $role_id);

            return $this->view->fetch();
        }
    }
    /**
     * 角色列表中的搜索功能
     */
    public function search_users($data)
    {
        if ($data['account']){
            $map['u.account'] = ['like','%'.$data['account'].'%'];
        }
        if ($data['realname']){
            $map['u.realname'] = ['like','%'.$data['realname'].'%'];
        }
        $role_id = $data['role_id'];
        $list= Db::name("admin_user_info")
                ->alias('u')
                ->join('tp_admin_role_user ru',"ru.user_id=u.id",'left')
                ->field('u.id,u.account,u.realname')
                ->where($map)
                ->where('u.status=1 AND u.id > 1')
                ->select();
        //查找其他的角色
        $other_role_user = Db::name('admin_role_user')->where('role_id','<>',$role_id)->field('user_id')->select();
        if (!empty($other_role_user)){
            $user_ids = '';
            foreach ($other_role_user as $ok=>$ov){
                $user_ids .= $ov['user_id'].',';
            }
            $user_ids =explode(',',rtrim($user_ids,','));
            if ($list){
                foreach ($list as $lk=>$lv){
                    if (in_array($lv['id'],$user_ids)){
                        unset($list[$lk]);
                    }
                }
            }
        }
        // 已授权权限
        $list_role_user = Db::name("admin_role_user")->where("role_id", $role_id)->select();
        $checks = filter_value($list_role_user, "user_id", true);
        foreach ($list as $k=>$v){
            $user_id[] = $v['id'];
        }
        if (empty($user_id)){
            $user_id = [];
        }
        $check_user = Db::name("admin_user_info")
            ->alias('u')
            ->join('tp_admin_role_user ru',"ru.user_id=u.id and ru.role_id=$role_id",'left')
            ->field('u.id,u.account,u.realname')
            ->where('u.status=1 AND u.id > 1 and ru.role_id='.$role_id)
            ->select();
        $check_user_id = [];
        foreach ($check_user as $ck=>$vk){
            if (in_array($vk['id'],$user_id)){
                $user[] = $check_user[$ck];
                $check_user_id[] = $vk['id'];
                unset($check_user[$ck]);
            }
        }
        foreach ($list as $kk=>$vv){
            if (in_array($vv['id'],$check_user_id)){
                unset($list[$kk]);
            }
        }
        $check_user = $user;
        $search['list'] = $list;
        $search['checks'] = $checks;
        $search['check_user'] = $check_user;
        return $search;
    }

    // 备份角色搜索功能
    public function search_users_beifen($data)
    {
        if ($data['account']){
            $map['u.account'] = ['like','%'.$data['account'].'%'];
        }
        if ($data['realname']){
            $map['u.realname'] = ['like','%'.$data['realname'].'%'];
        }
        $role_id = $data['role_id'];
        $list= Db::name("admin_user")
            ->alias('u')
            ->join('tp_admin_role_user ru',"ru.user_id=u.id",'left')
            ->field('u.id,u.account,u.realname')
            ->where($map)
            ->where('u.status=1 AND u.id > 1')
            ->select();
        //查找其他的角色
        $other_role_user = Db::name('admin_role_user')->where('role_id','<>',$role_id)->field('user_id')->select();
        if (!empty($other_role_user)){
            $user_ids = '';
            foreach ($other_role_user as $ok=>$ov){
                $user_ids .= $ov['user_id'].',';
            }
            $user_ids =explode(',',rtrim($user_ids,','));
            if ($list){
                foreach ($list as $lk=>$lv){
                    if (in_array($lv['id'],$user_ids)){
                        unset($list[$lk]);
                    }
                }
            }
        }
        // 已授权权限
        $list_role_user = Db::name("admin_role_user")->where("role_id", $role_id)->select();
        $checks = filter_value($list_role_user, "user_id", true);
        foreach ($list as $k=>$v){
            $user_id[] = $v['id'];
        }
        if (empty($user_id)){
            $user_id = [];
        }
        $check_user = Db::name("admin_user")
            ->alias('u')
            ->join('tp_admin_role_user ru',"ru.user_id=u.id and ru.role_id=$role_id",'left')
            ->field('u.id,u.account,u.realname')
            ->where('u.status=1 AND u.id > 1 and ru.role_id='.$role_id)
            ->select();
        $check_user_id = [];
        foreach ($check_user as $ck=>$vk){
            if (in_array($vk['id'],$user_id)){
                $user[] = $check_user[$ck];
                $check_user_id[] = $vk['id'];
                unset($check_user[$ck]);
            }
        }
        foreach ($list as $kk=>$vv){
            if (in_array($vv['id'],$check_user_id)){
                unset($list[$kk]);
            }
        }
        $check_user = $user;
        $search['list'] = $list;
        $search['checks'] = $checks;
        $search['check_user'] = $check_user;
        return $search;
    }
    /**
     * 授权
     * @return mixed
     */
    public function access()
    {
        $role_id = $this->request->param('id/d');
        if ($this->request->isPost()) {
            if (!$role_id) {
                return ajax_return_adv_error("缺少必要参数");
            }

            if (true !== $error = Loader::model('AdminAccess', 'logic')->insertAccess($role_id, $this->request->post())) {
                return ajax_return_adv_error($error);
            }
            return ajax_return_adv("权限分配成功", '');
        } else {
            if (!$role_id) {
                throw new Exception("缺少必要参数");
            }

            $tree = Loader::model('AdminRole', 'logic')->getAccessTree($role_id);
            $this->view->assign("tree", json_encode($tree));

            return $this->view->fetch();
        }
    }

    /**
     * 分配中止订单消息提示
     */
    public function add_suspended()
    {
        $data = input();
        $typeInfo = Db::name('information')->where('value',$data['type'])->find();
        if (!$typeInfo){
            return ajax_return_adv_error('不存在该信息');
        }
        if (!empty($typeInfo['role_ids'])){//存在角色
            $roleIds = '';
            $roleIds .= $typeInfo['role_ids'].','.$data['id'];
            $deal = Db::name('information')->where('id',$typeInfo['id'])->update(['role_ids'=>$roleIds]);
        }else{
            $deal = Db::name('information')->where('id',$typeInfo['id'])->update(['role_ids'=>$data['id']]);
        }
        if ($deal){
            return ajax_return_adv('添加成功');
        }else{
            return ajax_return_adv_error('添加失败');
        }
    }
    /**
     * 取消中止订单
     */
    public function cancel_suspended()
    {
        $data = input();
        $typeInfo = Db::name('information')->where('value',$data['type'])->find();
        if (!$typeInfo) {
            return ajax_return_adv_error('不存在该信息');
        }
        $roleIds = explode(',',$typeInfo['role_ids']);
        if (!in_array($data['id'],$roleIds)){
            return ajax_return_adv_error('该角色没有中止订单提示功能');
        }else{
            //去掉该角色id
            foreach ($roleIds as $rk=>$rv){
                if ($rv == $data['id']){
                    unset($roleIds[$rk]);
                }
            }
            $roleIds = implode(',',$roleIds);
            $up = Db::name('information')->where('id',$typeInfo['id'])->update(['role_ids'=>$roleIds]);
        }
        if ($up){
            return ajax_return_adv('取消成功');
        }else{
            return ajax_return_adv_error('取消失败');
        }
    }

    /**
     * 分配拒绝订单消息提示
     */
    public function add_refuse()
    {
        $data = input();
        $typeInfo = Db::name('information')->where('value',$data['type'])->find();
        if (!$typeInfo){
            return ajax_return_adv_error('不存在该信息');
        }
        if (!empty($typeInfo['role_ids'])){//存在角色
            $roleIds = '';
            $roleIds .= $typeInfo['role_ids'].','.$data['id'];
            $deal = Db::name('information')->where('id',$typeInfo['id'])->update(['role_ids'=>$roleIds]);
        }else{
            $deal = Db::name('information')->where('id',$typeInfo['id'])->update(['role_ids'=>$data['id']]);
        }
        if ($deal){
            return ajax_return_adv('添加成功');
        }else{
            return ajax_return_adv_error('添加失败');
        }
    }
    /**
     * 取消拒绝订单
     */
    public function cancel_refuse()
    {
        $data = input();
        $typeInfo = Db::name('information')->where('value',$data['type'])->find();
        if (!$typeInfo) {
            return ajax_return_adv_error('不存在该信息');
        }
        $roleIds = explode(',',$typeInfo['role_ids']);
        if (!in_array($data['id'],$roleIds)){
            return ajax_return_adv_error('该角色没有中止订单提示功能');
        }else{
            //去掉该角色id
            foreach ($roleIds as $rk=>$rv){
                if ($rv == $data['id']){
                    unset($roleIds[$rk]);
                }
            }
            $roleIds = implode(',',$roleIds);
            $up = Db::name('information')->where('id',$typeInfo['id'])->update(['role_ids'=>$roleIds]);
        }
        if ($up){
            return ajax_return_adv('取消成功');
        }else{
            return ajax_return_adv_error('取消失败');
        }
    }

    public function recyclebin()
    {
        $data = input();
        if ($data['name']){
            $map['name'] = ['like','%'.$data['name'].'%'];
        }
        $map['isdelete'] = 1;
        $list = Db::name('admin_role')->where($map)->select();
        $info = Db::name('information')->field('id,value,role_ids')->select();
        $infoArr = [];
        foreach ($info as $ik=>$iv){
            if (!empty($iv['role_ids'])){
                $infoArr[$iv['value']] = explode(',',$iv['role_ids']);
            }
        }
        $count = count($list);
        $this->view->assign('info',$infoArr);
        $this->view->assign('count',$count);
        $this->view->assign('list',$list);
        return $this->view->fetch();
    }

    /**
     * 添加请假消息提示
     */
    public function add_leave_message()
    {
        $data = input();
        $typeInfo = Db::name('information')->where('value',$data['type'])->find();
        if (!$typeInfo){
            return ajax_return_adv_error('不存在该信息');
        }
        if (!empty($typeInfo['role_ids'])){//存在角色
            $roleIds = '';
            $roleIds .= $typeInfo['role_ids'].','.$data['id'];
            $deal = Db::name('information')->where('id',$typeInfo['id'])->update(['role_ids'=>$roleIds]);
        }else{
            $deal = Db::name('information')->where('id',$typeInfo['id'])->update(['role_ids'=>$data['id']]);
        }
        if ($deal){
            return ajax_return_adv('添加成功');
        }else{
            return ajax_return_adv_error('添加失败');
        }
    }

    /**
     * 取消请假消息提示权限
     */
    public function cancel_leave_message()
    {
        $data = input();
        $typeInfo = Db::name('information')->where('value',$data['type'])->find();
        if (!$typeInfo) {
            return ajax_return_adv_error('不存在该信息');
        }
        $roleIds = explode(',',$typeInfo['role_ids']);
        if (!in_array($data['id'],$roleIds)){
            return ajax_return_adv_error('该角色没有请假消息提示功能');
        }else{
            //去掉该角色id
            foreach ($roleIds as $rk=>$rv){
                if ($rv == $data['id']){
                    unset($roleIds[$rk]);
                }
            }
            $roleIds = implode(',',$roleIds);
            $up = Db::name('information')->where('id',$typeInfo['id'])->update(['role_ids'=>$roleIds]);
        }
        if ($up){
            return ajax_return_adv('取消成功');
        }else{
            return ajax_return_adv_error('取消失败');
        }
    }
}
